package com.zpp.system.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zpp.common.core.constants.Constants;
import com.zpp.common.core.enums.ResultCode;
import com.zpp.common.security.exception.ServiceException;
import com.zpp.system.domain.question.Question;
import com.zpp.system.domain.question.dto.QuestionAddDTO;
import com.zpp.system.domain.question.dto.QuestionEditDTO;
import com.zpp.system.domain.question.dto.QuestionQueryDTO;
import com.zpp.system.domain.question.es.QuestionES;
import com.zpp.system.domain.question.vo.QuestionDetailVO;
import com.zpp.system.domain.question.vo.QuestionVO;
import com.zpp.system.elasticsearch.QuestionRepository;
import com.zpp.system.mapper.question.QuestionMapper;
import com.zpp.system.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        String excludeIdStr = questionQueryDTO.getExcludeIdStr();
        if(StrUtil.isNotEmpty(excludeIdStr)) {
            String[] excludeIdArr= excludeIdStr.split(Constants.SPLIT_SEM);
            Set<Long> excludeIdSet =  Arrays.stream(excludeIdArr)//转换成一个 Stream 流对象
                    .map(Long::valueOf) //对流中每个元素执行 Long.valueOf(x)，把字符串 转成 Long 类型
                    .collect(Collectors.toSet()); //把流中的元素收集成一个 Set 集合，去重且无序。
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }

        //设置分页
        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        return questionMapper.selectQuestionList(questionQueryDTO);
    }

    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
        //查询数据库中是否有同名题目
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .eq(Question::getTitle, questionAddDTO.getTitle()));
        //如果出现同名题目则抛出异常，返回异常信息为“资源已存在”
        if(CollectionUtil.isNotEmpty(questionList)) {
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }

        Question question = new Question();
        //1.将DTO转化为实体对象保存在数据库中
        BeanUtil.copyProperties(questionAddDTO, question);
        int result = questionMapper.insert(question);
        //表示插入失败
        if(result <= 0) {
            return false;
        }
        //2.再讲实体对象插入到ES当中
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question, questionES);
        questionRepository.save(questionES);
        return true;
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = verify(questionId);

        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        //对象转换
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question question = verify(questionEditDTO.getQuestionId());

        question.setTitle(questionEditDTO.getTitle());
        question.setDifficulty(questionEditDTO.getDifficulty());
        question.setContent(questionEditDTO.getContent());
        question.setTimeLimit(questionEditDTO.getTimeLimit());
        question.setSpaceLimit(questionEditDTO.getSpaceLimit());
        question.setQuestionCase(questionEditDTO.getQuestionCase());
        question.setDefaultCode(questionEditDTO.getDefaultCode());
        question.setMainFunc(questionEditDTO.getMainFunc());

        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question, questionES);
        questionRepository.save(questionES);  //save有新增也包含更新的功能

        return questionMapper.updateById(question);
    }

    @Override
    public int delete(Long questionId) {
        Question question = verify(questionId);

        //删除ES中的
        questionRepository.deleteById(questionId);
        //再删除数据库中的
        return questionMapper.deleteById(question);
    }

    //提前公共方法，校验id对应的题目是否存在，存在则返回对象
    public Question verify(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if(question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return question;
    }
}
